﻿package net.wangit.view.template;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.wangit.util.Checker;


/**
 * 页面模板
 * 
 * @author watson Feb 14, 2010
 */
public class Template {

	private List<String> pieces;
	private Map<Integer, Object> mapping;
	private Map units;
	private boolean hasAttributes;

	protected Template() {
		pieces = new ArrayList<String>();
		mapping = new HashMap<Integer, Object>();
	}

	public String combine(Map<String, String> attributes) {
		hasAttributes = false;
		StringBuffer result = new StringBuffer();
		if (pieces.size() == 1)
			hasAttributes = true;
		for (int i = 0; i < pieces.size(); i++) {
			String piece = pieces.get(i);
			result.append(piece);
			if (i < pieces.size() - 1) {
				Object key = mapping.get(new Integer(i));
				if (key instanceof Template) {
					Template t = (Template) key;
					String value = t.combine(attributes);
					if (t.isHasAttributes()) {
						hasAttributes = true;
						result.append(value);
					}
				} else {
					String value = (String) attributes.get(key);
					if (!Checker.isEmpty(value)) {
						hasAttributes = true;
						result.append(value);
					}
				}
			}
		}

		return hasAttributes ? result.toString() : "";
	}

	protected void setMapping(Map<Integer, Object> mapping) {
		this.mapping = mapping;
	}

	protected void setPieces(List<String> pieces) {
		this.pieces = pieces;
	}

	protected boolean isHasAttributes() {
		return hasAttributes;
	}

	public Map getUnits() {
		return units;
	}

	protected void setUnits() {
		units = new HashMap();
		setUnits(units);
	}

	protected void setUnits(Map units) {
		for (int i = 0; i < pieces.size() - 1; i++) {
			Object key = mapping.get(new Integer(i));
			if (key instanceof Template) {
				((Template) key).setUnits(units);
			} else if (((String) key).indexOf(",") > 0) {
				units.put(key, null);
			}
		}

	}
}
